// 获取元素
let $ = ele => document.querySelector(ele);

let getTop = $('.footer-top ul').children[2].children[0];
let main = $('#main');

// 加载中
let span = $("header>span")
// 在页面未加载完毕之前显示的loading Html自定义内容
let before = $('header span::before');
//监听加载状态改变
document.onreadystatechange = completeLoading;
//加载状态为complete时移除loading效果
function completeLoading() {
    if (document.readyState == "complete") {
        span.parentNode.removeChild(span);
    }
}

// 返回顶部
getTop.onclick = function (e) {
    // 阻止默认事件
    e.preventDefault();
    let distans = document.documentElement.scrollTop;
    let distansControl = setInterval(function () {
        distans -= 10;
        document.documentElement.scrollTop = distans;
        if (distans <= 0) {
            clearInterval(distansControl);
        }
    }, 3)
}

// 渲染品牌标题
function renderTitle(arr) {
    let html = '';
    arr.forEach(item => {
        html +=
            `<div class="main-title">
            <div class="main-title-top">
                <span>${item.brandTitle}</span>
                <span class="iconfont icon-xiangxia"></span>
            </div>
            <ul></ul>
        </div>`
    })
    return html;
}

// 渲染十大品牌
function renderBrand(arr) {
    let html = ''
    arr.forEach((item, index) => {
        html += `<li class="main-title-content">
        <a class="item" href='brand.html?brandtitleid=${item.brandId}&brandName=${item.brandName}'>
            <span>${index + 1}</span>
            <span>${item.brandName}</span>
            <p>${item.brandInfo}</p>
        </a>
    </li>`;

    })
    return html;
}

// 请求数据
const getTitle = () =>
    ajax({
        url: 'http://chst.vip:1234/api/getbrandtitle'
    })
getTitle().then(res => {
    res = res.result;
    main.innerHTML = renderTitle(res);
    let arr = [];
    res.forEach(item => {
        let p = fetch(`http://chst.vip:1234/api/getbrand?brandtitleid=${item.brandTitleId}`).then(body => body.json());
        arr.push(p);
    })
    return Promise.all(arr)
}).then(res => {
    let titles = main.children;
    res.forEach((item, index) => {
        let html = '';
        html = renderBrand(item.result);
        let ul = titles[index].children[1];
        ul.innerHTML += html;
    })

    titles = [...titles];
    for (let i = 0; i < titles.length; i++) {
        let flag = true;
        titles[i].children[0].onclick = function () {
            for (let j = 0; j < titles.length; j++) {
                titles[j].children[1].setAttribute('style', 'height : 0; overflow : hidden;');
            }
            if (flag) {
                this.nextElementSibling.setAttribute('style', 'height : 20.453333rem');
            } else {
                this.nextElementSibling.setAttribute('style', 'height : 0; overflow : hidden;');
            }
            flag = !flag;
        }
    }
})

